package com.foreveredu.propms.web.struts.action;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.Bill;
import com.foreveredu.propms.domain.ChargeRecord;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.Utilities;
import com.foreveredu.propms.service.IBusinessService;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.OwnerActionForm;

public class OwnerQueryAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;
	private IBusinessService businessService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IBusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	// 跳转到业主查询登陆界面
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("login");
	}

	// 通过房产编号和密码登陆业主详细页面
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		if (oaf.getHouseId() == null || "".equals(oaf.getHouseId())) {
			request.setAttribute("errorHouseId", "房产编号不能为空!");
			return mapping.findForward("login");
		}
		if (oaf.getPassword() == null || "".equals(oaf.getPassword())) {
			request.setAttribute("errorPassword", "密码不能为空!");
			return mapping.findForward("login");
		}
		Owner owner = managementService.findOwnerByHouseIdAndPassword(
				oaf.getHouseId(), oaf.getPassword());

		if (owner == null || "".equals(owner)) {
			request.setAttribute("errorOwner", "房产编号或密码填写错误，请核对后重新输入!");
			return mapping.findForward("login");
		}
		
		House house = managementService.findhouseByOwner(owner);
		request.setAttribute("house", house);
		request.setAttribute("owner", owner);
		return mapping.findForward("querySuccess");
	}

	// 显示业主的所有账单列表
	public ActionForward showALLBills(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);

		House house = managementService.findhouseByOwner(owner);

		// 列出该房产所有账单列表
		List<Bill> billList = new ArrayList<Bill>();

		billList = businessService.findBillsOfHouse(house);

		request.setAttribute("billList", billList);
		return mapping.findForward("showAllBills");
	}

	// 显示指定账单
	public ActionForward showBill(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;

		Bill bill = businessService.findBillById(Integer.parseInt(oaf
				.getBillId()));
		request.setAttribute("bill", bill);
		
		Owner owner = bill.getHouse().getOwner();
		request.setAttribute("owner", owner);
		
		// 获得该房产账单中的收费记录列表
		List<ChargeRecord> recordList = businessService
				.findChargeRecordsByBill(bill);
		request.setAttribute("recordList", recordList);

		// 获得该房产本月水电使用量
		Utilities utilities = businessService.findUtilitiesByHouseAndDate(
				bill.getHouse(), bill.getYear(), bill.getMonth());
		float powerBegin = utilities == null ? 0 : utilities.getPowerBegin();
		float powerEnd = utilities == null ? 0 : utilities.getPowerEnd();
		float powerVolume = powerEnd - powerBegin;

		float power2Begin = utilities == null ? 0 : utilities.getPower2Begin();
		float power2End = utilities == null ? 0 : utilities.getPower2End();
		float power2Volume = power2End - power2Begin;

		float waterBegin = utilities == null ? 0 : utilities.getWaterBegin();
		float waterEnd = utilities == null ? 0 : utilities.getWaterEnd();
		float waterVolume = waterEnd - waterBegin;

		float water2Begin = utilities == null ? 0 : utilities.getWater2Begin();
		float water2End = utilities == null ? 0 : utilities.getWater2End();
		float water2Volume = water2End - water2Begin;

		request.setAttribute("powerBegin", (int) powerBegin);
		request.setAttribute("powerEnd", (int) powerEnd);
		request.setAttribute("waterBegin", (int) waterBegin);
		request.setAttribute("waterEnd", (int) waterEnd);
		request.setAttribute("powerVolume", (int) powerVolume);
		request.setAttribute("waterVolume", (int) waterVolume);

		request.setAttribute("power2Begin", (int) power2Begin);
		request.setAttribute("power2End", (int) power2End);
		request.setAttribute("water2Begin", (int) water2Begin);
		request.setAttribute("water2End", (int) water2End);
		request.setAttribute("power2Volume", (int) power2Volume);
		request.setAttribute("water2Volume", (int) water2Volume);

		return mapping.findForward("showBill");
	}

	// 跳转到通过日期来查询账单
	public ActionForward toSearchBill(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;

		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);

		return mapping.findForward("toSearchBill");
	}

	// 跳转到通过日期来查询账单
	public ActionForward searchBill(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		OwnerActionForm oaf = (OwnerActionForm) form;

		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);

		House house = managementService.findhouseByOwner(owner);

		if (oaf.getChargeYear1().equals("0")
				|| oaf.getChargeYear2().equals("0")
				|| oaf.getChargeMonth1().equals("0")
				|| oaf.getChargeMonth2().equals("0")) {
			request.setAttribute("error", "请正确填写起止年份和月份");
			return mapping.findForward("toSearchBill");
		}
		if (Integer.parseInt(oaf.getChargeYear1()) > Integer.parseInt(oaf
				.getChargeYear2())) {
			request.setAttribute("error", "请正确填写起止年份和月份");
			return mapping.findForward("toSearchBill");
		}
		if (Integer.parseInt(oaf.getChargeYear1()) == Integer.parseInt(oaf
				.getChargeYear2())
				&& Integer.parseInt(oaf.getChargeMonth1()) > Integer
						.parseInt(oaf.getChargeMonth2())) {
			request.setAttribute("error", "请正确填写起止年份和月份");
			return mapping.findForward("toSearchBill");
		}

		int y1 = Integer.parseInt(oaf.getChargeYear1());
		int y2 = Integer.parseInt(oaf.getChargeYear2());
		int m1 = Integer.parseInt(oaf.getChargeMonth1());
		int m2 = Integer.parseInt(oaf.getChargeMonth2());

		// 列出该房产所有账单列表
		List<Bill> billList = new ArrayList<Bill>();

		if (y1 == y2) {
			for (int i = m1; i <= m2; i++) {
				Bill bill = businessService.findBillByHouseAndMonth(house, y1,i);
				if (bill != null && !"".equals(bill)) {
					billList.add(bill);
				}
			}
		}
		if (y2 > y1) {
			for (int i = m1; i <= 12; i++) {
				Bill bill = businessService.findBillByHouseAndMonth(house, y1,i);
				if (bill != null && !"".equals(bill)) {
					billList.add(bill);
				}
			}
			if (y2 - y1 > 1) {
				for (int k = 1; y2 - y1 > k; k++) {
					for (int i = 1; i < 12; i++) {
						Bill bill = businessService.findBillByHouseAndMonth(house, y1 + k, i);
						if (bill != null && !"".equals(bill)) {
							billList.add(bill);
						}
					}
				}
			}
			for (int i = 1; i <= m2; i++) {
				Bill bill = businessService.findBillByHouseAndMonth(house, y2,i);
				if (bill != null && !"".equals(bill)) {
					billList.add(bill);
				}
			}

		}
		request.setAttribute("billList", billList);
		return mapping.findForward("showAllBills");
	}
	
	// 跳转到业主信息修改界面
	public ActionForward toUpdateOwner(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		OwnerActionForm oaf = (OwnerActionForm) form;
		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);
		
		return mapping.findForward("toUpdateOwner");
	}
	
	// 跳转到业主信息修改界面
	public ActionForward updateOwnerSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		OwnerActionForm oaf = (OwnerActionForm) form;
		Owner owner = managementService.findOwnerById(oaf.getId());
		
		// 表单校验
		if (!oaf.getIdCard().equals(
				(managementService.findOwnerById(oaf.getId()).getIdCard()))) {// 校验身份证是否修改过，如若修改过再向下继续校验

			if (oaf.getIdCard() == null || "".equals(oaf.getIdCard())) {
				request.setAttribute("owner", owner);
				request.setAttribute("error", "请输入身份证号");

				return mapping.findForward("toUpdateOwner");
			} else {
				// 对输入的身份证号码进行校验
				Pattern p = Pattern
						.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z|a-z])$");
				Matcher m = p.matcher(oaf.getIdCard());
				if (!m.matches()) {
					request.setAttribute("owner", owner);
					request.setAttribute("error", "身份证号码输入有误！");
					return mapping.findForward("toUpdateOwner");
				} else {
					if (managementService.findOwnerByIdCard(oaf.getIdCard()) != null) {
						request.setAttribute("owner", owner);
						request.setAttribute("error",
								"该身份证号已注册，请核对后重新输入！");
						return mapping.findForward("toUpdateOwner");
					}
				}
			}
		}
		if (oaf.getPhone() == null || "".equals(oaf.getPhone())) {
			request.setAttribute("owner", owner);
			request.setAttribute("error", "请输入联系电话");

			return mapping.findForward("toUpdateOwner");
		} else {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
			Matcher m = p.matcher(oaf.getPhone());
			if (!m.matches()) {
				request.setAttribute("owner", owner);
				request.setAttribute("error", "请输入有效的联系电话！");
				return mapping.findForward("toUpdateOwner");
			}
		}
		if (oaf.getPassword() == null || "".equals(oaf.getPassword())) {
			request.setAttribute("owner", owner);
			request.setAttribute("error", "请输入登录密码");

			return mapping.findForward("toUpdateOwner");
		}

		
		
		
		oaf.setName(owner.getName());
		PropertyUtils.copyProperties(owner, oaf);
		managementService.updateOwner(owner);
		
		House house = managementService.findhouseByOwner(owner);
		request.setAttribute("house", house);
		request.setAttribute("owner", owner);
		
		return mapping.findForward("querySuccess");
	}
			
	public ActionForward opinion(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		OwnerActionForm oaf = (OwnerActionForm) form;

		Owner owner = managementService.findOwnerById(oaf.getId());
		request.setAttribute("owner", owner);
		
		House house = managementService.findhouseByOwner(owner);
		request.setAttribute("house", house);

		return mapping.findForward("opinion");
	}

}